package cn.tedu.front.search.dao.search.impl;

import cn.tedu.common.pojo.vo.PageData;
import cn.tedu.front.search.dao.search.IJobCustomSearchRepository;
import cn.tedu.front.search.dao.search.IJobSearchRepository;
import cn.tedu.front.search.pojo.po.JobSimplePO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class JobSearchRepository implements IJobSearchRepository {
    @Autowired
    private IJobCustomSearchRepository customSearchRepository;

    @Override
    public PageData<JobSimplePO> jobSearch(String keyword, Integer pageNum, Integer pageSize) {
        pageNum--;
        Pageable pageable= PageRequest.of(pageNum,pageSize);
        SearchPage<JobSimplePO> searchHits = customSearchRepository.jobSearch(keyword, pageable);
        SearchHits<JobSimplePO> hits = searchHits.getSearchHits();

        PageData<JobSimplePO> pageData=new PageData<>();
        pageData.setMaxPage(pageNum++);
        pageData.setPageSize(pageSize);
        pageData.setMaxPage(searchHits.getTotalPages());
        pageData.setTotal(hits.getTotalHits());

        List<JobSimplePO> list=new ArrayList<>();
        for (SearchHit<JobSimplePO> hit : hits) {
            JobSimplePO hitContent = hit.getContent();
            List<String> highlightField = hit.getHighlightField("salary");
            if (highlightField.size()>0){
              hitContent.setSalary(highlightField.get(0));
            }
            list.add(hitContent);
        }
        pageData.setList(list);
        return pageData;
    }
}
